package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 分享游戏
type ShareGame struct {
	BaseM
	Uid        bson.ObjectId     `bson:"_id" json:"_id"`               // 用户uid
	ShareCode  string            `bson:"shareCode" json:"shareCode"`   // 分享码
	FriendCode string            `bson:"friendCode" json:"friendCode"` // 邀请的好友分享码
	FriendUid  map[string]string `bson:"friendUid" json:"friendUid"`   // 领过分享码的玩家uid
}

func NewShareGame() cache.EntryI {
	return &ShareGame{
		FriendUid: make(map[string]string),
	}
}

// 保存信息
func (this *ShareGame) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("ShareGame", bson.M{"_id": this.Uid}, this)
	if err != nil {
		return err
	}
	return
}

func (this *ShareGame) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		this.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		this.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "ActPack_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return this.LoadData()
}

// 加载数据
func (this *ShareGame) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("ShareGame", bson.M{"_id": this.Uid}, nil, &this)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

// 更新数据
func (this *ShareGame) Update(val *ShareGame) {
	Cache.Put("ShareGame", val.Uid.Hex(), val)
	val.UpdateData()
}

func (this *User) GetShareGame() (r *ShareGame) {
	v, _ := Cache.Get("ShareGame", this.Uid.Hex())
	r = v.(*ShareGame)
	return
}

func FindShareGameByShareCode(shareCode string) (shareGame *ShareGame, err error) {
	shareGame = &ShareGame{}
	err = dbmodule.MgoDB.GameDB.FindOne("ShareGame", bson.M{"shareCode": shareCode}, nil, &shareGame)
	return
}
